package com.tronsis.distribution.activity.goods;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.CartBean;
import com.tronsis.distribution.biz.factory.ProductBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.KeyboardUtils;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.ConfirmDialog;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * allen: 添加限额数量
 * 进货单
 */
public class ReceiptActivity extends ToolBarBaseActivity {

    @BindView(R.id.rv_goods)
    RecyclerView mRvGoods;
    @BindView(R.id.tv_more)
    TextView mTvMore;
    @BindView(R.id.tv_amount)
    TextView mTvAmount;


    private CommonAdapter<CartBean> mAdapter;
    private List<CartBean> mGoodsList = new ArrayList<>();
    private List<CartBean> mGoodsAllList = new ArrayList<>();
    private List<CartBean> mGoodsPartList = new ArrayList<>();

    private Dialog mInputDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receipt);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.receipt));

        initRv();

        getCartList();
    }


    private void initRv() {
        mAdapter = new CommonAdapter<CartBean>(mContext, mGoodsList, R.layout.item_goods_order) {
            @Override
            protected void convert(final ViewHolder holder, final CartBean cartBean, final int position) {
                holder.setImageByUrl(mContext, R.id.iv_cover, Url.FILE_DOWNLOAD + cartBean.getCoverFid());
                if (StateUtil.getResSate(mContext, cartBean.getState()).equals("已下架")) {
                    holder.setText(R.id.tv_state, StateUtil.getResSate(mContext, cartBean.getState()));
                    holder.setVisible(R.id.tv_state, true);
//                    holder.setVisible(R.id.tv_total, false);
                } else {
                    holder.setVisible(R.id.tv_state, false);
//                    holder.setVisible(R.id.tv_total, true);
                }
                holder.setText(R.id.tv_product_name, cartBean.getName());
//                holder.setText(R.id.tv_total, "可进货数量：" + String.valueOf(cartBean.getAllowCount()));
                holder.setText(R.id.tv_amount, String.valueOf(cartBean.getAmount()));

                final TextView tvCount = holder.getView(R.id.tv_amount);
                holder.getView(R.id.tv_subtract).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 减号按钮，减少商品数量
                        int count = Integer.valueOf(tvCount.getText().toString());
                        if (count > 1) {
                            count--;
                            tvCount.setText(count + "");
                            updateCartNum(cartBean.getCartId(), count);
                            return;
                        }
                        if (count == 1) {
                            showDeleteDialog(tvCount, cartBean.getCartId());
                        }
                    }
                });
                holder.getView(R.id.tv_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // allen：增加可进货商品数量
                        // 1.库存数量：当库存数量为0时代理商无法进货；库存数量由后台填写；库存不足时提示：“商品名称”库存不足
                        // 2. 进货限制：针对各级各类代理商设置一个线上库存限额，如果超过此限额则不能进货；如A产品的县级限额为10，
                        // 则他的进货订单中A的数量及现有的线上库存的A的数量之和不能超过10。此限额后台统一确定。
                        int count = Integer.valueOf(tvCount.getText().toString());
//                        if (Integer.valueOf(cartBean.getStock()) < count) {
//                            ToastUtil.showToastInCenter(mContext, "进货数量不能超过" + cartBean.getStock());
//                            return;
//                        }
                        tvCount.setText(++count + "");
                        updateCartNum(cartBean.getCartId(), count);

                    }
                });

                holder.setOnClickListener(R.id.tv_amount, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showInputDialog(String.valueOf(cartBean.getAmount()), cartBean.getCartId());
                    }
                });

                holder.setOnLongClickListener(R.id.cl_item, new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        showDeleteDialog(cartBean.getCartId());
                        return false;
                    }
                });
            }
        };


        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvGoods.addItemDecoration(decoration);
        mRvGoods.setLayoutManager(new LinearLayoutManager(mContext));
        mRvGoods.setHasFixedSize(true);
        mRvGoods.setNestedScrollingEnabled(false);
        mRvGoods.setAdapter(mAdapter);
    }

    @OnClick(R.id.tv_more)
    void onMoreClick() {
        if (mGoodsList.size() > 6) {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsPartList);
            mTvMore.setText(getString(R.string.format_view_all_goods, mGoodsAllList.size()));
        } else {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsAllList);
            mTvMore.setText("收起");
        }


        mAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.btn_submit)
    void submitClick() {
        if (mGoodsAllList.isEmpty()) {
            ToastUtil.showMessage(mContext, "请先添加商品至进货单");
            return;
        }
        //Allen add
        for (CartBean cartBean : mGoodsAllList) {
            if (StateUtil.getResSate(mContext, cartBean.getState()).equals("已下架")) {
                ToastUtil.showToastInCenter(mContext, "含下架产品，请删除后重新添加");
                return;
            }
            if (cartBean.getAllowCount() > 0 && cartBean.getAllowCount() < cartBean.getAmount()) {
                ToastUtil.showToastInCenter(mContext, "库存不足");
                return;
            }
        }
        httpSubmit();
    }

    private void showInputDialog(String count, final String cartId) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_input_num, null);
        mInputDialog = new AlertDialog.Builder(this).setView(view).create();
        final EditText et = view.findViewById(R.id.et_num);
        et.setText(count);
        et.setSelection(et.getText().length());


        ImageButton imbClose = view.findViewById(R.id.mbt_close);
        imbClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mInputDialog.dismiss();
            }
        });

        Button btnOk = view.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(et.getText().toString().trim())) {
                    ToastUtil.showMessage(mContext, "请输入数量");
                    return;
                }
//                if (Integer.valueOf(stock) < Integer.valueOf(et.getText().toString().trim())) {
//                    ToastUtil.showMessage(mContext, "超出商品库存");
//                    return;
//                }
                int count = Integer.valueOf(et.getText().toString().trim());
                updateCartNum(cartId, count);
                KeyboardUtils.hideSoftInput(et);
                mInputDialog.dismiss();
            }
        });

        Button btnCancel = view.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mInputDialog.dismiss();
            }
        });

        mInputDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            public void onShow(DialogInterface dialog) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
            }

        });
        mInputDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                KeyboardUtils.hideSoftInput(et);
            }
        });

        mInputDialog.show();

    }

    private void showDeleteDialog(final String cartId) {
        ConfirmDialog dialog = new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {

            }

            @Override
            public void onRightButtonClick(View view) {
                httpDeleteCart(cartId);

            }
        });
        dialog.showDialog("确认删除？", "取消", "确定");
    }

    private void showDeleteDialog(final TextView tv, final String cartId) {
        ConfirmDialog dialog = new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {
                tv.setText("1");
            }

            @Override
            public void onRightButtonClick(View view) {
                httpDeleteCart(cartId);

            }
        });
        dialog.showDialog("确认删除？", "取消", "确定");
    }

    private void getCartList() {
        try {
            ProductBizFactory.createBiz().getCartList(this, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    List<CartBean> list = (List<CartBean>) data;
                    mGoodsAllList.clear();
                    mGoodsList.clear();
                    mGoodsPartList.clear();
                    mGoodsAllList.addAll(list);
                    mTvMore.setText(getString(R.string.format_view_all_goods, mGoodsAllList.size()));
                    if (mGoodsAllList.size() > 6) {
                        mTvMore.setVisibility(View.VISIBLE);
                        for (int i = 0; i < 6; i++) {
                            mGoodsPartList.add(mGoodsAllList.get(i));
                        }
                        mGoodsList.addAll(mGoodsPartList);
                    } else {
                        mGoodsList.addAll(mGoodsAllList);
                    }
                    mAdapter.notifyDataSetChanged();
                    double priceSum = 0;
                    for (CartBean cartBean : mGoodsAllList) {
//                        priceSum = priceSum + cartBean.getPrice() * cartBean.getAmount() + cartBean.getFreight() * cartBean.getAmount();
                        priceSum = priceSum + cartBean.getPrice() * cartBean.getAmount();
                    }
                    mTvAmount.setText(getString(R.string.format_rmb, priceSum));
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void updateCartNum(String cartId, int amount) {
        try {
            ProductBizFactory.createBiz().updateCartNum(this, cartId, amount, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    getCartList();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpDeleteCart(String cartId) {
        try {
            ProductBizFactory.createBiz().deleteCart(this, cartId, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    getCartList();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                    getCartList();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            getCartList();
            e.printStackTrace();
        }

    }


    private void httpSubmit() {
        try {
            ProductBizFactory.createBiz().submitCart(this, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
//                    ToastUtil.showMessage(mContext, "提交成功，请去我的--我的订单--我的进货页面进行订单支付");
                    dismissLoadingDialog();
//                    finish();
                    showDialog();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void showDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_receipt_confirm, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(view).create();
        dialog.setCancelable(false);
        TextView btnOk = view.findViewById(R.id.tv_ok);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.show();
    }
}
